package foodmaterial.action;

import com.github.pagehelper.PageHelper;
import foodmaterial.entity.JsonResult;
import foodmaterial.entity.SysUser;
import foodmaterial.excel.Excel;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BaseAction {
    @ExceptionHandler
    public JsonResult exp(HttpServletRequest request, Exception ex) {
        request.setAttribute("ex1", ex);
        ex.printStackTrace();
        return new JsonResult(false,ex.getMessage());
    }

    void setDownload(HttpServletResponse response, Excel excel) throws IOException {
        response.setContentType("application/application/vnd.ms-excel");
        String fileName = excel.nextId() + ".xlsx" ;
        response.setHeader("Content-disposition","attachment;filename=" +
                new String(fileName.getBytes("GBK"),"iso-8859-1"));
    }

    void setDownload(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=" +
                new String(fileName.getBytes("GBK"),"iso-8859-1"));
    }

    SysUser getSysUser() {
        return (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    void setPageHelper(Integer pageNo,Integer pageSize) {
        if (pageNo != null && pageSize != null) {
            PageHelper.startPage(pageNo,pageSize) ;
        } else {
            PageHelper.startPage(1,2000) ;
        }
    }
}
